package com.xzz.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * @author: hhz
 * @create: 2021-12-20 13:42
 * 652 寻找重复的子树
 * 给定一棵二叉树，返回所有重复的子树。对于同一类的重复子树，你只需要返回其中任意一棵的根结点即可。
 * 两棵树重复是指它们具有相同的结构以及相同的结点值。
 **/
public class FindDuplicateSubtrees {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {
        }
        TreeNode(int val) {
            this.val = val;
        }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
//        TreeNode node1 = new TreeNode(1);
//        TreeNode node2 = new TreeNode(2);
//        TreeNode node3 = new TreeNode(3);
//        TreeNode node4 = new TreeNode(4);
//        TreeNode node5 = new TreeNode(2);
//        TreeNode node6 = new TreeNode(4);
//        TreeNode node7 = new TreeNode(4);
//        node1.left = node2;
//        node1.right = node3;
//        node2.left = node4;
//        node3.left = node5;
//        node3.right = node6;
//        node5.left = node7;
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(1);
        TreeNode node3 = new TreeNode(1);

        node1.left = node2;
        node1.right = node3;
        List<TreeNode> duplicateSubtrees = findDuplicateSubtrees(node1);
        for (TreeNode node : duplicateSubtrees) {
            System.out.println(node.val);
        }
    }

    public static List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        List<TreeNode> res = new ArrayList<>();
        HashMap<String,Integer> treeStrMap = new HashMap<>();
        String s = find(root,res,treeStrMap);
        System.out.println(s);
        return res;
    }
    public static String find(TreeNode root,List<TreeNode> res,HashMap<String,Integer> treeStrMap) {
        if(root==null){
            return "#";
        }
        String left = find(root.left,res,treeStrMap);
        String right = find(root.right,res,treeStrMap);
        String treeStr = left+","+right+","+root.val;
        Integer orDefault = treeStrMap.getOrDefault(treeStr, 0);
        if(orDefault == 1){
            res.add(root);
        }
        treeStrMap.put(treeStr,1+orDefault);

        return treeStr;
    }

}
